Approach for improving runtime of Python function

welcome to shbcf.ru